package cn.edu.gzhu.workOrderManagement.exceptionHandle;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.exception.parameterException;
import cn.edu.gzhu.workOrderManagement.result.Result;
import cn.hutool.json.JSONException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandle {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler(parameterException.class)
    public Result parameterException(parameterException e) {
        log.error(e.getMessage());
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result bindHandle(BindException bindException) {
        log.error(bindException.getMessage());
       return Result.error(bindException.getBindingResult().getFieldError().getField()+ bindException.getBindingResult().getFieldError().getDefaultMessage());
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result httpHandle(HttpMessageNotReadableException e) {
        log.error(e.getMessage());
        return Result.error(MessageConstant.JSON_ERROR);
    }
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result sqlHandle(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        return Result.error(MessageConstant.PARAMETER_ERROR);
    }

    @ExceptionHandler(JSONException.class)
    public Result jsonHandle(JSONException e) {
        log.error(e.getMessage());
        return Result.error(MessageConstant.PARAMETER_ERROR);
    }
    @ExceptionHandler(InvalidFormatException.class)
    public Result invalidFormatHandle(InvalidFormatException e) {
        log.error(e.getMessage());
        return Result.error(MessageConstant.JSON_ERROR);
    }


    @ExceptionHandler(DuplicateKeyException.class)
    public Result duplicateException(DuplicateKeyException e) {
        return Result.error(MessageConstant.NAME_REPEAT);
    }

    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandle(Exception e) {
        return Result.error(e.getMessage());
    }






}
